// 沉降数据，每2分钟1个（7+2字节）
define(function(require){
	var $ = require("jquery");
	var justep = require("$UI/system/lib/justep");
	var echarts = require("../lib/echarts/echarts-all-min");
	var tt = require("$UI/demo/misc/importJs/noneAMD1");
	var mqtt = require("../mqttclient/mqtt-baidu");
	require("../lib/moment.min");

	var comm = require('../lib/user/comm');
	 
	
	var Model = function(){
		this.callParent();
		this.chart = null;
		this.chartData = [];
		this.chartxAxis = [];		// chart 的  X 轴坐标点
		this.chartDataMax = 10;		// chart X方向最多数据个数； 1分钟 一个数据
		this.dataCounter = 0;       // 接收的数据个数
		this.chartHeight = justep.Bind.observable('200px');  // 默认 chart 高度
		
		this.timerChartRender = null;
	};

    Model.prototype.test = function() {
    	alert('test ok');
    };

	Model.prototype.doMsgArrivedGrating = function (message) {
		//justep.Util.hint('grating data arrived');
		var rr = this.chartAppend(message.payloadBytes);
    };

	// 将数据保存到 this.chartData 中，并绘制 chart； buff=收到的 7+2字节数据包
    Model.prototype.chartAppend = function(buff) {
    	//  
		var vb = new Uint8Array(buff);
		var year = vb[0] + vb[1]*256;
		var time = moment([year, vb[2]-1, vb[3], vb[4], vb[5], vb[6], 0]); // 初始化是月从0开始；0=1月
		var val = vb[7] + vb[8]*256;
		var tt = moment(time).format('HH:mm');

	    this.dataAppend(tt, val);
	    this.dataRender();

		return {time: time};
    };

	// 将数据保存到 this.chartData 中；timestr=x轴; val=y轴
    Model.prototype.dataAppend = function(timestr, val) {
    	var data = {
    		name: timestr,
    		value: [ timestr, val ]
    	};
    	
    	if(this.dataCounter === 0) {
    		this.chartxAxis.splice(0, this.chartxAxis.length); //清空数组 
    		this.chartData.splice(0, this.chartData.length); //清空数组 
    		
    		for (var i=0; i<this.chartDataMax; i++) {
    			this.chartxAxis.push(' ');
    			this.chartData.push(0);
    		}
    	}
    	
    	if (this.dataCounter < this.chartDataMax) {
    		this.chartxAxis[this.dataCounter] = timestr;
    		this.chartData[this.dataCounter] = val;
    	} else {
	    	while(this.chartData.length >= this.chartDataMax) {
	    		this.chartData.shift();
	    		this.chartxAxis.shift();
	    	}
	    	
	    	this.chartxAxis.push(timestr);
	        this.chartData.push(val);
    	}
    	
        this.dataCounter = this.dataCounter + 1;
    	return data;
    };
    
	// 在 chart 上绘制 this.chartData 数据
    Model.prototype.dataRender = function() {
	    this.chart.setOption({
	    	xAxis: [{data: this.chartxAxis}],
	        series: [{
	            data: this.chartData
	        }]
	    });
    };
    
    Model.prototype.chartInit = function(chartHeight) {
        var option = {
        	title: {
        		text: '沉降检测',
        		left: '36px',
        		textStyle: {
        			fontSize: '14',
        		}
        	},
		    grid: {
		        left: '36px',
		        right: '20px',
		        top: '10px',
		        bottom: '20px',
		        containLabel: false
		    },
            toolbox: {
                show : true,
                feature : {
                    mark : {show: true},
                    dataView : {show: false, readOnly: false},
                    magicType : {show: false, type: ['line', 'bar']},
                    restore : {show: true},
                    saveAsImage : {show: true}
                }
            },

            tooltip : {
                trigger: 'axis'
            },
            
		    xAxis: [{
		        type: 'category',
		        data: [], 
		    }],
		    
		    yAxis: {
		        type: 'value',
		        scale: false,
		        max: 120,
		        boundaryGap: [0, '100%'],
		        splitLine: {
		            show: false
		        }
		    },
		    
		    series: [{
		        name: '实时数据',
		        type: 'bar',
		        showSymbol: false,
		        hoverAnimation: false,
		        label:{ 
		        	normal:{ 
		        	show: true, 
		        	position: 'top'} // inside, top
		        },
		        data: this.chartData
		    }],
            
            legend: {
                data:['实时数据','其它']
            },

            calculable : true,

        };
        
		this.chartHeight.set(chartHeight);
        this.chart = echarts.init(this.getElementByXid('pnlChart'));
        var myChart = this.chart;
        myChart.setOption(option);
    };
    
    Model.prototype.modelLoad = function(event) {
    	var ch;
    	if(this.params.chartHeight)
    	{
    		ch = this.params.chartHeight;
    	}
    	else
    	{
        	ch = (window.innerHeight * 0.28).toFixed() + 'px';
    	}
    	this.chartInit(ch);


        var self = this;
		mqtt.onMsgArrivedGrating = function(message) { self.doMsgArrivedGrating(message);};
    };
    
	Model.prototype.modelUnLoad = function(event){
		mqtt.Unsubscribe(comm.gParams.baiduTopics.grating + '/#');
	};
    
	Model.prototype.modelActive = function(event){
		mqtt.Subscribe(comm.gParams.baiduTopics.grating + '/#', 0);
	};
    
	return Model;
}
);